package com.sunlands.deskmate.web;


import com.sunlands.deskmate.client.LiveVideoService;
import com.sunlands.deskmate.client.UserFriendService;
import com.sunlands.deskmate.constant.AppEnum;
import com.sunlands.deskmate.domain.MessageSystemDO;
import com.sunlands.deskmate.enums.MessageType;
import com.sunlands.deskmate.service.MessageService;
import com.sunlands.deskmate.vo.*;
import com.sunlands.deskmate.vo.response.BusinessResult;
import com.sunlands.deskmate.vo.response.PageResultVO;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import io.swagger.annotations.ApiParam;
import jodd.util.StringUtil;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.security.access.prepost.PreAuthorize;
import org.springframework.web.bind.annotation.*;

import javax.servlet.http.HttpServletRequest;
import java.util.*;
import java.util.concurrent.CompletableFuture;
import java.util.stream.Collectors;

/**
 * @author shixiaopeng
 */
@SuppressWarnings("unused")
@Api(tags = "消息接口")
@Slf4j
@RestController
public class MessageController extends BaseController {

    @Autowired
    private MessageService messageService;

    @Autowired
    private UserFriendService userFriendService;

    @Autowired
    private LiveVideoService liveVideoService;

    @ApiOperation(value = "发送消息接口--多个用户/单个群--服务端内部调用")
    @PostMapping("/message")
    public BusinessResult createMessagePerson(HttpServletRequest request, @RequestBody MessageDTO messageDTO) {

        String headers = getHeaders(request);
        log.info("发送消息接口--多个用户/单个群--服务端内部调用" + "：url = {} params = {} headers = {} user = {}", "/message", messageDTO.toString(), headers, "");
        String result = checkData(messageDTO);
        if (result != null) {
            return BusinessResult.createInstance(CommonResultMessage.PARAMS_NOT_INVALIDE, result);
        }
        //异步处理
        CompletableFuture.runAsync(() -> {
            if (messageDTO.getIsGroupSend() != null && messageDTO.getIsGroupSend()) {
                messageService.createGroup(messageDTO);

            } else {
                messageService.createPerson(messageDTO);
            }
        });

        return BusinessResult.createSuccessInstance(null);
    }

    private String getHeaders(HttpServletRequest request) {
        Enumeration<String> enumeration = request.getHeaderNames();
        StringBuilder headers = new StringBuilder();
        while (enumeration.hasMoreElements()) {
            String name = enumeration.nextElement();
            String value = request.getHeader(name);
            headers.append(name).append(":").append(value).append(",");
        }
        return headers.toString();
    }

    @ApiOperation(value = "给所有用户发系统消息")
    @PostMapping("/all/user/message")
    public BusinessResult createMessage(@RequestBody MessageDTO messageDTO) {
        log.info("给所有用户发系统消息messageDTO = {} ", messageDTO);

        //异步处理
        CompletableFuture.runAsync(() -> {
            messageService.createMessageForAll(messageDTO);
        });

        return BusinessResult.createSuccessInstance(null);
    }

    @ApiOperation(value = "根据用户id获取消息列表--app前端调用")
    @PreAuthorize("isAuthenticated()")
    @GetMapping("/message")
    public BusinessResult<List<Message>> getMessageList(HttpServletRequest request, @RequestParam Integer userId) {
        log.info("根据用户id获取消息列表 = {}", userId);
        String app = getApp(request);
        List<Message> messageList = messageService.getMessageList(userId);

        //如果是考研自习室app，屏蔽群消息
        if (app.equals(AppEnum.postgraduate.name())) {
            messageList = messageList.stream().filter(m ->
                    {
                        if (m.getType().equals(MessageType.DYNAMIC_MESSAGE.getType()) && StringUtil.isNotBlank(m.getTitle()))
                            return !m.getTitle().contains("创建了群")
                                    && !m.getTitle().contains("选择了新的学习目标")
                                    && !m.getTitle().contains("删除了学习目标");
                        else
                            return !m.getType().startsWith("2")
                                    && !m.getType().equals(MessageType.SHARE_GROUP_TO_PRIVATE.getType())
                                    && !m.getType().equals(MessageType.TARGET_SELECT_ME.getType())
                                    && !m.getType().equals(MessageType.TARGET_SELECT_FRIEND.getType());
                    }
            ).collect(Collectors.toList());
        }
        return BusinessResult.createSuccessInstance(messageList);
    }

    private String getApp(HttpServletRequest request) {
        String app = request.getHeader("app");
        app = (Objects.nonNull(app) && AppEnum.postgraduate.name().equals(app)) ?
                AppEnum.postgraduate.name() : AppEnum.tongzhuo.name();
        return app;
    }

    @ApiOperation(value = "根据用户id获取消息列表--app前端调用")
    @PreAuthorize("isAuthenticated()")
    @GetMapping("/test")
    public BusinessResult<List<Message>> test(@RequestParam Integer userId) {
        log.info("根据用户id获取消息列表 = {}", userId);
        List<Message> messageList = messageService.test(userId);
        return BusinessResult.createSuccessInstance(messageList);
    }

    @ApiOperation(value = "根据用户id获取系统历史消息列表--分页--app前端调用")
    @PreAuthorize("isAuthenticated()")
    @GetMapping("/message/_system")
    public BusinessResult<PageResultVO<MessageSystemDO>> getMessageList(@ApiParam(value = "用户id") @RequestParam Integer userId,
                                                                        @ApiParam(value = "页码") @RequestParam(defaultValue = "1") Integer page,
                                                                        @ApiParam(value = "页码大小") @RequestParam(defaultValue = "10") Integer pageSize) {
        PageResultVO<MessageSystemDO> systemMessagePages = messageService.findSystemMessagePages(userId, page, pageSize);
        return BusinessResult.createSuccessInstance(systemMessagePages);
    }

    private String checkData(MessageDTO messageDTO) {
        if (messageDTO.getIsGroupSend() == null || !messageDTO.getIsGroupSend()) {
            List<Integer> userIds = messageDTO.getUserIds();
            if (userIds == null || userIds.size() == 0) {
                return "userId不能为空";
            }
        }
        return null;
    }

    @ApiOperation(value = "获取用户的道友的连麦状态--app前端调用")
    @PreAuthorize("isAuthenticated()")
    @GetMapping("/message/live-state")
    public BusinessResult<List<Message>> liveState() {
        Long userId = currentUserId();
        log.info("获取用户的道友的连麦状态 = {}", userId);
        return BusinessResult.createSuccessInstance(messageService.liveState(userId));
    }

}
